const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

function init() {
  canvas.width = window.innerWidth * devicePixelRatio
  canvas.height = window.innerHeight * devicePixelRatio
}

init()

const fontSize = 16 * devicePixelRatio
ctx.font = `${fontSize}px Roboto Mono`

const column = Math.floor(canvas.width / fontSize)
const charIndex = new Array(column).fill(0)

function getRandomChar() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+~`|}{[]:;?><,./-='
  return chars.charAt(Math.floor(Math.random() * chars.length))
}

function getRandomColor() {
  const r = Math.floor(Math.random() * 256)
  const g = Math.floor(Math.random() * 256)
  const b = Math.floor(Math.random() * 256)
  const a = Math.random().toFixed(2)

  // 避免生成完全黑色的颜色
  if (r === 0 && g === 0 && b === 0) {
    return getRandomColor()
  }
  // 避免生成完全白色的颜色
  if (r === 255 && g === 255 && b === 255) {
    return getRandomColor()
  }
  // 避免生成完全透明的颜色
  if (a === '0.00') {
    return getRandomColor()
  }
  return `rgba(${r}, ${g}, ${b}, ${a})`
}

function draw() {
  ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  ctx.fillStyle = getRandomColor()
  ctx.textBaseline = 'top'
  for (let i = 0; i < column; i++) {
    const char = getRandomChar()
    const x = i * fontSize
    const y = charIndex[i] * fontSize
    ctx.fillText(char, x, y)
    if (y > canvas.height - fontSize && Math.random() > 0.99) {
      charIndex[i] = 0
    }
    charIndex[i]++
  }
}

draw()

setInterval(() => {
  draw()
}, 50)